//
//  ILGLocation.m
//  WangHuo
//
//  Created by zhangtongle on 2017/5/23.
//  Copyright © 2017年 ifeng. All rights reserved.
//

#import "ILGLocation.h"

typedef void(^IWHLocationCallback)(ILGLocationItem *locationInfo);

@interface ILGLocation () <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;

@property (nonatomic, copy) IWHLocationCallback callback;
@end

@implementation ILGLocation
+ (instancetype)sharedInstance {
    static ILGLocation *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ILGLocation alloc] init];
        
        if ([CLLocationManager locationServicesEnabled]) {
            if (!manager.locationManager) {
                manager.locationManager = [[CLLocationManager alloc] init];
                manager.locationManager.delegate = manager;
            }
            
            if ([manager.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [manager.locationManager requestWhenInUseAuthorization];
            }
        }
    });
    
    return manager;
}

- (NSString *)cityName
{
    if (self.locationInfo.cityName.length > 0) {
        return self.locationInfo.cityName;
    } else {
        return @"";
    }
}

- (CLAuthorizationStatus)status {
    return [CLLocationManager authorizationStatus];
}

- (void)currentLocation:(void(^)(ILGLocationItem *locationInfo))callback {
    _callback = callback;
    self.locationInfo = [[ILGLocationItem alloc] init];

    if ([CLLocationManager locationServicesEnabled]) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
            self.locationInfo.error = [NSError errorWithDomain:@"com.ILGLocation.error" code:IWHLocationErrorDeny userInfo:@{NSLocalizedDescriptionKey:@"用户拒绝使用定位服务"}];
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(self.locationInfo);
            });

        } else {
            [self.locationManager startUpdatingLocation];

        }
        
    } else {
        self.locationInfo.error = [NSError errorWithDomain:@"com.ILGLocation.error" code:IWHLocationErrorUnLock userInfo:@{NSLocalizedDescriptionKey:@"用户未打开定位服务"}];
        callback(self.locationInfo);
    }
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations{
    //此处locations存储了持续更新的位置坐标值，取最后一个值为最新位置，如果不想让其持续更新位置，则在此方法中获取到一个值之后让locationManager stopUpdatingLocation
    CLLocation *currentLocation = [locations lastObject];
    
    CLLocationCoordinate2D coordinate = currentLocation.coordinate;
    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
    _locationInfo.latitude = [NSString stringWithFormat:@"%f", coordinate.latitude];
    _locationInfo.longitude = [NSString stringWithFormat:@"%f", coordinate.longitude];
    _locationInfo.cityName = @"";
    
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    
    //根据经纬度反向地理编译出地址信息
    __weak typeof(self)weakSelf = self;
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error) {
        if (array.count > 0){
            
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            //获取城市，四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            NSString *city = placemark.addressDictionary[@"City"];
            if (!city){
                city = placemark.administrativeArea;
            }
            weakSelf.locationInfo.cityName = city;
            
        } else if (error == nil && [array count] == 0) {
            NSLog(@"No results were returned.");
            weakSelf.locationInfo.error = [NSError errorWithDomain:@"com.ILGLocation.error" code:IWHLocationErrorResultNil userInfo:@{NSLocalizedDescriptionKey:@"返回结果为空"}];
            
        } else if (error != nil) {
            NSLog(@"An error occurred = %@", error);
            weakSelf.locationInfo.error = error;
            
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.callback ? weakSelf.callback(weakSelf.locationInfo):nil;
            weakSelf.callback = nil;
        });
    }];
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];

}
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    self.locationInfo.error = error;
    
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakSelf.callback ? weakSelf.callback(weakSelf.locationInfo):nil;
        weakSelf.callback = nil;
    });
}
@end
